package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //1.接收手机号封装User对象
        //2.生成4位手机验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        System.out.println("本次生成的验证码："+code);

        //3.发送手机验证码
        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972","18620624601",code);

        //4.将生成的验证码存储到session中（手机号作为key，验证码作为value）
        session.setAttribute(user.getPhone(),code);

        //5.返回数据，输出成功
        return R.success("验证码已发送");
    }

    @Autowired(required = false)
    private UserService userService;

    //处理登录请求
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map, HttpSession session){

        //1.接收数据封装到Map<String,String> map
        String phone = map.get("phone");
        String code = map.get("code");

        //2.从session中获取存储的验证码
        String sessionCode = (String) session.getAttribute(phone);


        //3.调用业务层进行登录操作,返回登录的用户对象
        User loginUser = userService.login(phone, code, sessionCode);

        //4.登录用户有效，写入session（key="user"）
        if(loginUser!=null){
            session.setAttribute("user",loginUser);
        }

        //5.返回数据（登录的用户）
        return R.success(loginUser);
    }

    @PostMapping("/loginout")
    public R loginout(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        session.invalidate();
        return R.success("退出成功");
    }

}
